// 3.6 查询sdp发送结果
use reqwest::Client;
use serde::{Deserialize};
use anyhow::{anyhow, Result};
use crate::api::get_stream_token::get_stream_token;
use crate::api::get_session_id::get_session_id;

#[derive(Debug, Deserialize)]
struct SdpResponse {
    exchangeResponse: String,
    errorDetails: ErrorDetails,
}

#[derive(Debug, Deserialize)]
struct ErrorDetails {
    code: Option<String>,
    message: Option<String>,
}

#[derive(Debug, Deserialize)]
struct Exchange {
    sdp: String,
    sdpType: String,
    status: String,
    // 你可以根据需要添加更多字段，如 chat、control 等
}
pub async fn get_sdp() -> Result<String>{
    println!("get_sdp function start");
    let client = Client::new();
    let stream_token = get_stream_token().await?;
    let Authorization = format!("Bearer {}", stream_token);
    let session_id = get_session_id(None).await?;
    let url = format!("https://xhome.gssv-play-prod.xboxlive.com/v5/sessions/home/{}/sdp", session_id);
    let response = client.get(url)
        .header("Content-Type", "application/json")
        .header("Authorization", Authorization)
        .send().await?;
    let response_code = response.status().as_u16();
    let response_body = response.text().await?;
    if response_code != 200 {
        println!("failed to get sdp, response code: {response_code}");
        return Err(anyhow!("failed to get sdp, response code: {response_code}"));
    }
    println!("get_sdp response body: {}", response_body);

    let response: SdpResponse = serde_json::from_str(&response_body)?;
    let response = response.exchangeResponse;
    let response: Exchange = serde_json::from_str(&response)?;
    let sdp = response.sdp;
    return Ok(sdp);
}